package com.example.demo.leetcode.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class SortPut {


    private static ReentrantLock reentrantLock = new ReentrantLock();


    public static void main(String[] args) throws InterruptedException {
        Condition condition1 = reentrantLock.newCondition();
        Condition condition2 = reentrantLock.newCondition();
        Condition condition3 = reentrantLock.newCondition();
        Reader reader1 = new Reader("A",condition1,condition2);
        Thread thread1 = new Thread(reader1);
        Reader reader2 = new Reader("B",condition2,condition3);
        Thread thread2 = new Thread(reader2);
        Reader reader3 = new Reader("C",condition3,condition1);
        Thread thread3 = new Thread(reader3);

        thread1.start();
        thread2.start();
        thread3.start();

        Thread.sleep(1000);
        reentrantLock.lock();
        try {
            condition1.signal();
        }finally {
            reentrantLock.unlock();
        }
    }

    static class Reader implements  Runnable{

        private String name;
        private Condition a;
        private Condition b;

        public Reader(String name,Condition a,Condition b) {
            this.name = name;
            this.a = a;
            this.b = b;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            for(int i=0;i<10;i++){
                reentrantLock.lock();
                try {

                    a.await();
                    String myNmae = Thread.currentThread().getName();
                    System.out.println(myNmae+"reading");
                    b.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    reentrantLock.unlock();
                }

            }
        }
    }
}
